package com.xindacloud.sms.portal.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {

    public static boolean isMobile(String mobiles) {
        Pattern p = Pattern.compile("^((\\+86)|(86))?[1][3456789][0-9]{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static String buildRandomUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String buildAlphanumeric() {
        return RandomStringUtils.randomAlphanumeric(17);
    }


    public static boolean isUnicode(String src) {
        if (StringUtils.isNotEmpty(src)) {
            int length = src.getBytes(StandardCharsets.UTF_8).length;
            if (length > src.length()) {
                return true;
            }
        }
        return false;
    }


    public static Integer calcMessageCount(String messageBody) {
        if (StringUtils.isEmpty(messageBody)) {
            return 0;
        }
        return isUnicode(messageBody) ? calcCountFor(messageBody, 70, 63) : calcCountFor(messageBody, 160, 153);
    }

    private static Integer calcCountFor(String str, int firstScalar, int secondScalar) {
        Integer initCount = 1;
        if (str.length() <= firstScalar) {
            return initCount;
        } else {
            String substring = str.substring(firstScalar);
            final int subStrLength = substring.length();
            int batchCount = subStrLength / secondScalar + (subStrLength % secondScalar == 0 ? 0 : 1);
            batchCount = initCount + batchCount;
            return batchCount;
        }
    }


    public static Map<String, Object> buildYYResult(Integer code, String msg, String msgid) {

        Map<String, Object> buildResultMap = new HashMap<>();
        buildResultMap.put("code", code);
        buildResultMap.put("msg", msg);
        buildResultMap.put("msgid", msgid);
        return buildResultMap;
    }

    public static String encodeMD5(String text) {
        //加密后的字符串
        final String md5Hex = DigestUtils.md5Hex(text);
        return md5Hex;
    }
}
